package room;

import org.apache.mina.core.future.CloseFuture;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.Scanner;

/**
 * Created by hasee on 2016/9/23.
 */
public class MinaClient {
    private static final int PORT = 9123;
    private IoSession session;
    private NioSocketConnector connector;
    private ConnectFuture future;
    public static void main(String[] args) throws Throwable  {
        MinaClient client = new MinaClient();
        if (client.connect()) {
            client.send("连接服务器成功！");
            Scanner sc = new Scanner(System.in);
            while (true){
                String mes = sc.nextLine();
                client.send(mes);
            }

        }
    }

    public boolean connect(){
        connector = new NioSocketConnector();
        // 设置连接超时检查时间
        connector.setConnectTimeoutCheckInterval(30);

        connector.getFilterChain().addLast("codec",
                new ProtocolCodecFilter(new TextLineCodecFactory( Charset.forName( "UTF-8" ))));

        connector.getFilterChain().addLast("logger", new LoggingFilter());
        connector.setHandler(new MinaClientHandler());
        future = connector.connect(new InetSocketAddress("127.0.0.1", PORT));
        future.awaitUninterruptibly();
        session = future.getSession();
        return true;
    }
    public void setAttribute(Object key, Object value) {
        session.setAttribute(key, value);
    }

    public void send(String message) {
        session.write(message);
    }

    public boolean close() {
        CloseFuture future = session.getCloseFuture();
        future.awaitUninterruptibly(1000);
        connector.dispose();
        return true;
    }

    public NioSocketConnector getConnector() {
        return connector;
    }

    public IoSession getSession() {
        return session;
    }
}
